package com.SouthernWall_404.AgeSuitcase.Client.Gui.Screens;

import com.SouthernWall_404.AgeSuitcase.Client.Gui.Buttons.TransformableImageButton;
import com.SouthernWall_404.AgeSuitcase.Client.Gui.Buttons.TransformablePlainTextButton;
import com.SouthernWall_404.AgeSuitcase.Common.API.GeneralAPI;
import com.SouthernWall_404.AgeSuitcase.Common.API.GuiAPI.Animation.*;
import com.SouthernWall_404.AgeSuitcase.Common.API.GuiSoundHelper;
import com.SouthernWall_404.AgeSuitcase.Common.API.StorageAPI;
import com.SouthernWall_404.AgeSuitcase.Common.AgeSuitcase;
import com.SouthernWall_404.AgeSuitcase.Common.init.ModSounds;
import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.User;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.LogoRenderer;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.*;
import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.MusicManager;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;

import javax.annotation.Nullable;
import java.util.Date;
import java.util.List;

public class LoginScreen extends Screen {

//    public static final CubeMap CUBE_MAP = new CubeMap(new ResourceLocation("textures/gui/title/background/panorama"));
    public static ResourceLocation START_SCREEN;
    public static String LOGIN_SUCCESS;
    public static final ResourceLocation BUTTONS=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/loginbuttons.png");
    public static final ResourceLocation UIS=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/ui.png");
    public static final ResourceLocation LOGO=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/logo.png");
//    private final PanoramaRenderer panorama;
    private static final String GUI=GeneralAPI.GUI+"loginscreen.";

    private static final List<String> VERSION_INFO=StorageAPI.loadStringFromRoot("version_info");
    private final boolean fading;
    private long fadeInStart;


    private SoundInstance theme= SimpleSoundInstance.forUI(ModSounds.LOGIN_SCREEN_MUSIC.get(),1f,1f);
    private SoundManager soundManager=Minecraft.getInstance().getSoundManager();


    private boolean isStartingQuitComfirm=false;
    private boolean isComfirmingQuit =false;
    private boolean isCancelingQuitComfirm=false;
    private TransformableImageButton quitComfirmBackGround;
    private TransformablePlainTextButton quitOrNotText;
    private FadingIn quitComfirmBackGroundFadingIn;;
    private FadingIn quitOrNotTextFadingIn;
    private FadingOut quitComfirmBackGroundFadingOut;
    private FadingOut quitOrNotTextFadingOut;

    private TransformableImageButton quitCancel;
    private TransformablePlainTextButton quitCancelText;
    private TransformableImageButton quitComfirm;
    private TransformablePlainTextButton quitComfirmText;
    private MoveTo quitComfirmTextFadingIn;;
    private MoveTo quitCancelTextFadingIn;
    private MoveTo quitComfirmFadingIn;;
    private MoveTo quitCancelFadingIn;
    private MoveTo quitComfirmTextFadingOut;
    private MoveTo quitCancelTextFadingOut;
    private MoveTo quitComfirmFadingOut;
    private MoveTo quitCancelFadingOut;

    private boolean test=false;

    private MoveTo loginBackGroundMoveIn;
    private MoveTo loginBackGroundMoveOut;
    private MoveTo loginPlayerHeadMoveOut;
    private MoveTo loginPlayerHeadMoveIn;
    private MoveTo loginTextMoveIn;
    private MoveTo loginTextMoveOut;
    private int loginStartX;
    private int loginStartY;
    private TransformableImageButton loginSuccessTag;
    private TransformableImageButton loginPlayerHead;
    private TransformablePlainTextButton loginSuccessText;
    private boolean hasShown=false;

    private TransformableImageButton settingButton;
    private TransformableImageButton quitButton;
    private TransformableImageButton socialButton;

    private TransformablePlainTextButton startText;
    private Breathing startTextBreathe;
    private TransformableImageButton start;

    private TransformableImageButton startDeco1;
    private TransformableImageButton startDeco2;

    private boolean isStarting=false;
    private int tick=0;

    private TransformablePlainTextButton copyRightButton;
    private TransformablePlainTextButton versionInfoButton;

    private TransformableImageButton logo;

    private int time=0;


//    private final LogoRenderer logoRenderer;
    public LoginScreen() {
        this(false);
    }

    public LoginScreen(boolean p_96733_) {
        this(p_96733_, (LogoRenderer)null);
    }

    public LoginScreen(boolean p_265779_, @Nullable LogoRenderer p_265067_) {
        super(Component.translatable("narrator.screen.title"));
//        this.panorama = new PanoramaRenderer(CUBE_MAP);

        this.fading = p_265779_;



//        GuiSoundHelper.playLoadingFinish();
//        this.logoRenderer = (LogoRenderer) Objects.requireNonNullElseGet(p_265067_, () -> new LogoRenderer(false));
    }

    public void quitComfirmStart()
    {
        this.isStartingQuitComfirm=true;
//        this.isComfirmingQuit=true;

        linkQuitComfirmAnimation();
    }

    public void quitComfirmCancel() {

        this.isComfirmingQuit=false;
        this.isCancelingQuitComfirm=true;

        this.removeWidget(quitComfirmBackGround);
        this.removeWidget(quitOrNotText);
        this.removeWidget(quitComfirm);
        this.removeWidget(quitComfirmText);
        this.removeWidget(quitCancel);
        this.removeWidget(quitCancelText);

        this.rebuildWidgets();

        this.quitComfirmBackGroundFadingOut=new FadingOut(quitComfirmBackGround);
        this.quitOrNotTextFadingOut=new FadingOut(quitOrNotText);
        this.quitComfirmFadingOut=new MoveTo(quitComfirm,quitComfirm.getX(),quitComfirm.getY()+5,10);
        this.quitCancelFadingOut=new MoveTo(quitCancel,quitCancel.getX(),quitCancel.getY()+5,10);
        this.quitComfirmTextFadingOut=new MoveTo(quitComfirmText,quitComfirmText.getX(),quitComfirmText.getY()+5,10);
        this.quitCancelTextFadingOut=new MoveTo(quitCancelText,quitCancelText.getX(),quitCancelText.getY()+5,10);


    }
    public void quitComfirmRenderer(GuiGraphics guiGraphics,int mouseX,int mouseY,float partialTick)
    {

        if(isCancelingQuitComfirm)
        {
            quitComfirmBackGroundFadingOut.tick(guiGraphics,partialTick);
            quitOrNotTextFadingOut.tick(guiGraphics,partialTick);
            quitComfirmFadingOut.tick(guiGraphics,partialTick);
            quitCancelFadingOut.tick(guiGraphics,partialTick);
            quitComfirmTextFadingOut.tick(guiGraphics,partialTick);
            quitCancelTextFadingOut.tick(guiGraphics,partialTick);

            if(quitComfirmBackGroundFadingOut.isFinished()&&quitOrNotTextFadingOut.isFinished())
            {

                this.isCancelingQuitComfirm=false;

                initQuitComfirm();
            }
            return; // 添加 return 语句，避免后续渲染
        }

        if(isComfirmingQuit){//动画完成.渲染正式内容
//            RenderSystem.enableBlend();0 
//            guiGraphics.fill(0,0,this.width,this.height,0x292421FF);
            guiGraphics.pose().pushPose();
            // 重置颜色为不透明
//            guiGraphics.setColor(1.0f, 1.0f, 1.0f, 1.0f);
            quitComfirmBackGround.render(guiGraphics,mouseX,mouseY,partialTick);
            quitOrNotText.render(guiGraphics,mouseX,mouseY,partialTick);
            if(quitCancelFadingIn.isFinished()&&quitComfirmFadingIn.isFinished())
            {
//                this.addRenderableWidget()
                quitComfirm.render(guiGraphics,mouseX,mouseY,partialTick);//这样不会闪烁
                quitCancel.render(guiGraphics,mouseX,mouseY,partialTick);
//                this.addRenderableWidget(quitCancel);
//                this.addRenderableWidget(quitComfirm);
            }

            quitComfirmText.render(guiGraphics,mouseX,mouseY,partialTick);
            quitCancelText.render(guiGraphics,mouseX,mouseY,partialTick);
            guiGraphics.pose().popPose();
            return; // 添加 return 语句，避免后续渲染
        }
        if(isStartingQuitComfirm)//正在打开退出确认，渲染动画
        {
//            RenderSystem.enableBlend();

            quitComfirmBackGroundFadingIn.tick(guiGraphics,partialTick);
            quitOrNotTextFadingIn.tick(guiGraphics,partialTick);
            quitCancelTextFadingIn.tick(guiGraphics,partialTick);
            quitComfirmTextFadingIn.tick(guiGraphics,partialTick);
            quitCancelFadingIn.tick(guiGraphics,partialTick);
            quitComfirmFadingIn.tick(guiGraphics,partialTick);
            if(quitComfirmBackGroundFadingIn.isFinished()&&quitOrNotTextFadingIn.isFinished())
            {
                quitCancel.render(guiGraphics,mouseX,mouseY,partialTick);
                this.isStartingQuitComfirm=false;
                this.isComfirmingQuit=true;
            }

            return; // 添加 return 语句，避免后续渲染
        }


    }
    public void getTime()
    {
        Date date = new Date(System.currentTimeMillis());

        int hour=date.getHours();
        if(hour>=6&&hour<9) {//6:00-9:00早晨
            START_SCREEN=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/login_morning.png");
            LOGIN_SUCCESS=GUI+"morning_login";
        }
        if(hour>=9&&hour<13){//9:00-18:00白天
            START_SCREEN=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/login_noon.png");
            LOGIN_SUCCESS=GUI+"noon_login";
        }
        if(hour>=13&&hour<18){//9:00-18:00白天
            START_SCREEN=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/login_afternoon.png");
            LOGIN_SUCCESS=GUI+"afternoon_login";
        }
        if(hour>=18||hour<6)//18:00-次日6:00夜晚
        {
            START_SCREEN=new ResourceLocation(AgeSuitcase.MODID,"textures/gui/screen/login/login_evening.png");
            LOGIN_SUCCESS=GUI+"evening_login";
        }
    }


        @Override
    public void renderBackground(GuiGraphics guiGraphics) {



        getTime();
        guiGraphics.blit(START_SCREEN,0,0,width,height,0f,0f,1904,944,1904,944);
            this.logo.render(guiGraphics,0,0,0);
        if(isComfirmingQuit||isStartingQuitComfirm||isCancelingQuitComfirm)
        {
            guiGraphics.fill(0,0,this.width,this.height,0x292421FF);
        }

    }

    public boolean isPauseScreen() {
        return false;
    }

    public boolean shouldCloseOnEsc() {
        return false;
    }

    @Override
    protected void removeWidget(GuiEventListener p_169412_) {
        super.removeWidget(p_169412_);
    }

    @Override
    protected void init() {
        // 必须调用父类初始化
        super.init();

        getTime();

        initSideBar();
        initAnouncement();
        initQuitComfirm();
        initLoginSuccessComfirm();
        initStartButton();
        // 添加必要的按钮和元素

        // 添加更多按钮...\
        this.addRenderableWidget(socialButton);
        this.addRenderableWidget(quitButton);
        this.addRenderableWidget(settingButton);
        this.addRenderableWidget(copyRightButton);
        this.addRenderableWidget(versionInfoButton);


        // 处理淡入效果
        if (this.fading) {
            this.fadeInStart = Util.getMillis();
        }
    }
    private void initStartButton()
    {
        Component START_TEXT=Component.translatable(GUI+"press_to_start");

        int length=this.font.width(START_TEXT.getString());
        int height=this.font.lineHeight;

        this.start=new TransformableImageButton((this.width-length-16)/2,this.height*3/4-8,length,height,0,480,0,length+16,height+16,UIS,512,512,button ->start());
        this.startText =new TransformablePlainTextButton((this.width-length)/2,this.height*3/4,length,height,START_TEXT, b->{},this.font,1,0xffffff,false);

        this.startDeco1=new TransformableImageButton((this.width-length)/2-48-10,this.height*3/4+height/2,48,1,0,80,0,48,1, UIS,512,512,button -> {});
        this.startDeco2=new TransformableImageButton((this.width+length)/2+10,this.height*3/4+height/2,48,1,0,80,0,48,1, UIS,512,512,button -> {});

        this.startTextBreathe=new Breathing(this.startText,300);



        int logoHeight=this.height/3;
        int logoLength=logoHeight*2;

        this.logo=new TransformableImageButton((this.width-logoLength)/2,(this.height)/3,1043,447,0,0,0,logoLength,LOGO,1043,447,b->{});
    }

    private void start()
    {
        this.isStarting=true;
//        this.minecraft.setScreen(new LoadingScreen(Component.empty(),new SelectWorldScreen(this),100));
    }

    private void initLoginSuccessComfirm()
    {
        Minecraft mc=Minecraft.getInstance();
        User user =mc.getUser();
        SkinManager skinManager=mc.getSkinManager();

        GameProfile playerProfile=user.getGameProfile();

        ResourceLocation SKIN=skinManager.getInsecureSkinLocation(playerProfile);

        Component LOGINSUCCESS_TEXT=Component.translatable(LOGIN_SUCCESS,user.getName());
        int loginSuccessTextLength=this.font.width(LOGINSUCCESS_TEXT);
        int loginSuccessTextHeight=this.font.lineHeight;
        int loginSuccessBackGroundLength=loginSuccessTextLength+20;
        int loginSuccessBackGroundHeight=loginSuccessTextHeight+8;
        loginSuccessTag=new TransformableImageButton((this.width-loginSuccessBackGroundLength)/2,(this.height)/8,96,32,0,32,0,loginSuccessBackGroundLength,loginSuccessBackGroundHeight,UIS,512,512,b->{});
        loginSuccessText=new TransformablePlainTextButton((this.width)/2-loginSuccessTextLength/2+6, (this.height)/8+4,loginSuccessTextLength, loginSuccessTextHeight, LOGINSUCCESS_TEXT,button -> {},this.font,1f,0x9B8063);
        this.loginPlayerHead=new TransformableImageButton((this.width-loginSuccessBackGroundLength)/2+4,(this.height)/8+4,8,8,8,8,0,8,8,SKIN,64,64,b->{});

        this.loginStartX=(this.width-loginSuccessBackGroundLength)/2;
        this.loginStartY=-loginSuccessBackGroundHeight;
        this.loginBackGroundMoveOut=new MoveTo(loginSuccessTag,this.loginStartX,this.loginStartY,40);
        this.loginBackGroundMoveIn =new MoveTo(this.loginStartX,this.loginStartY,loginSuccessTag,40,new Wait(loginSuccessTag,80,this.loginBackGroundMoveOut));

        this.loginStartX=(this.width)/2-loginSuccessTextLength/2+6;
        this.loginStartY=-loginSuccessBackGroundHeight+4;
        this.loginTextMoveOut=new MoveTo(loginSuccessText,this.loginStartX,this.loginStartY,40);
        this.loginTextMoveIn =new MoveTo(this.loginStartX,this.loginStartY,loginSuccessText,40,new Wait(loginSuccessText,80,this.loginTextMoveOut));

        this.loginStartX=(this.width-loginSuccessBackGroundLength)/2+4;
        this.loginStartY=-loginSuccessBackGroundHeight+4;
        this.loginPlayerHeadMoveOut=new MoveTo(loginPlayerHead,this.loginStartX,this.loginStartY,40);
        this.loginPlayerHeadMoveIn =new MoveTo(this.loginStartX,this.loginStartY,loginPlayerHead,40,new Wait(loginPlayerHead,80,this.loginPlayerHeadMoveOut));

    }
    private void initQuitComfirm()
    {
        Component QUITORNOT_TEXT = Component.translatable(GUI+"quit_or_not");
        int quitOrNotLength=this.font.width(QUITORNOT_TEXT);
        int quitOrNotHeight=this.font.lineHeight;


        quitComfirmBackGround=new TransformableImageButton(0,this.height/2-16,512,32,0,0,0,this.width,UIS,512,512,button -> {});
        quitOrNotText=new TransformablePlainTextButton((this.width-quitOrNotLength*3/2)/2, (this.height)/2-8,quitOrNotLength, quitOrNotHeight, QUITORNOT_TEXT,button -> {},this.font,1.5f,0x9B8063);
        quitCancel=new TransformableImageButton((this.width)/2-48-5,this.height/2+18,48,16,0,64,0,48,16,UIS,512,512,b->{this.quitComfirmCancel();});
        quitComfirm=new TransformableImageButton((this.width)/2+5,this.height/2+18,48,16,48,64,0,48,16,UIS,512,512,b->{this.minecraft.stop();});
        Component COMFIRM_TEXT=Component.translatable(GUI+"comfirm");
        int length=this.font.width(COMFIRM_TEXT);
        int height=this.font.lineHeight;
        quitComfirmText=new TransformablePlainTextButton((this.width)/2+5+(48-length)/2, this.height/2+18+(16-height)/2,length, height, COMFIRM_TEXT,button -> {},this.font,1f,0x9B8063);
        Component CANCEL_TEXT=Component.translatable(GUI+"cancel");
        length=this.font.width(CANCEL_TEXT);
        height=this.font.lineHeight;
        quitCancelText=new TransformablePlainTextButton((this.width)/2-48-5+(48-length)/2, this.height/2+18+(16-height)/2,length, height, CANCEL_TEXT,button -> {},this.font,1f,0x9B8063);




        linkQuitComfirmAnimation();
    }
    public void linkQuitComfirmAnimation()
    {
        quitComfirmBackGroundFadingIn =new FadingIn(quitComfirmBackGround,15);
        quitOrNotTextFadingIn =new FadingIn(quitOrNotText,15);//淡入绑定
        quitComfirmTextFadingIn =new MoveTo(quitComfirmText.getX(),quitComfirmText.getY()+5,quitComfirmText,15);
        quitCancelTextFadingIn =new MoveTo(quitCancelText.getX(),quitCancelText.getY()+5,quitCancelText,15);
        quitComfirmFadingIn =new MoveTo(quitComfirm.getX(),quitComfirm.getY()+5,quitComfirm,15);
        quitCancelFadingIn =new MoveTo(quitCancel.getX(),quitCancel.getY()+5,quitCancel,15);

        quitComfirmFadingIn.fixMode=true;
        quitCancelFadingIn.fixMode=true;
        quitComfirmTextFadingIn.fixMode=true;
        quitCancelTextFadingIn.fixMode=true;
    }
    private void initSideBar()
    {
        socialButton=new TransformableImageButton(this.width-18,this.height-54,64,64,0,192,0,16,16,BUTTONS,512,512, button ->{});
        quitButton=new TransformableImageButton(this.width-18,this.height-18,64,64,0,64,0,16,16,BUTTONS,512,512, button ->this.quitComfirmStart());
        settingButton=new TransformableImageButton(this.width-18,this.height-36,64,64,0,128,0,16,16,BUTTONS,512,512, button ->this.minecraft.setScreen(new LoadingScreen(Component.empty(),new PauseScreen(true),120)));
    }
    private void initAnouncement()
    {
        Component COPYRIGHT_TEXT = Component.translatable(GUI+"copyright");
        Component VERSION_CODE_TEXT=Component.empty();
        if(VERSION_INFO.size()!=0)
        {
            VERSION_CODE_TEXT=Component.translatable(GUI+"version_info",VERSION_INFO.get(0));
        }


        copyRightButton=new TransformablePlainTextButton(0, this.height-this.font.lineHeight/2,this.font.width(COPYRIGHT_TEXT), 10, COPYRIGHT_TEXT,button -> {this.openCopyRight();},this.font,0.5f,0xFFFFFFFF);
        versionInfoButton=new TransformablePlainTextButton(0, 0,this.font.width(VERSION_CODE_TEXT), 10, VERSION_CODE_TEXT,button ->{},this.font,0.5f,0xFFFFFFFF,false);

    }

    private void onChange()
    {
        this.soundManager.stop(theme);
    }

    @Override
    public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {


        PoseStack poseStack=guiGraphics.pose();
//        this.addRenderableWidget(this.startTest);

        if(!soundManager.isActive(theme))
        {
            theme= SimpleSoundInstance.forUI(ModSounds.LOGIN_SCREEN_MUSIC.get(),1f,1f);

            soundManager.play(theme);
        }

        if(!fading)
        {
            time++;
        }
        this.renderBackground(guiGraphics);


//        this.addRenderableWidget(this.logo);


//        this.addRenderableWidget(this.startDeco1);
//        this.addRenderableWidget(this.startDeco2);

        this.startTextBreathe.tick(guiGraphics,partialTick);
        this.addRenderableWidget(start);
        if(!hasAccount()&&!hasShown&&time>=60)
        {
            this.loginBackGroundMoveIn.tick(guiGraphics,partialTick);
            this.loginTextMoveIn.tick(guiGraphics,partialTick);
            this.loginPlayerHeadMoveIn.tick(guiGraphics,partialTick);

            if(this.loginBackGroundMoveOut.isFinished()&&loginTextMoveOut.isFinished()&&loginPlayerHeadMoveOut.isFinished())
            {
                hasShown=true;
            }
        }
        super.render(guiGraphics, mouseX, mouseY, partialTick);
        //guiGraphics.drawString(this.font, Component.translatable(GUI+"press_to_start"), this.width/2-30, this.height*2/3, 0xFFFFFF);
        quitComfirmRenderer(guiGraphics,mouseX,mouseY,partialTick);
        if (isStarting)
        {
            int fadingTime=10;
            tick++;

           float fadeOutProgress = Math.min(1.0f, (float) tick /fadingTime);

            // 绘制半透明黑色覆盖层实现淡出效果
            int alpha = (int) (fadeOutProgress * 200); // 最大透明度为200（约78%）
            guiGraphics.fill(0, 0, this.width, this.height, (alpha << 24));
            if(tick>=fadingTime)
            {
                onChange();
                minecraft.setScreen(new LoadingScreen(Component.empty(),new OperateScreen(Component.empty()),120));
            }
        }
    }
    public void openCopyRight()
    {

        this.minecraft.setScreen(new CreditsAndAttributionScreen(this));
    }
    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {

        if (super.mouseClicked(mouseX, mouseY, button)) {
            return true;
        }

        // 处理退出确认组件的点击事件
        if (isComfirmingQuit) {
            if (quitCancel.isMouseOver(mouseX, mouseY)) {
                quitCancel.mouseClicked(mouseX, mouseY,button);
                return true;
            }

            if (quitComfirm.isMouseOver(mouseX, mouseY)) {
                quitComfirm.mouseClicked(mouseX, mouseY,button);
                return true;
            }
        }

        if(!isCancelingQuitComfirm&&!isStartingQuitComfirm&&!isCancelingQuitComfirm&&start.isMouseOver(mouseX,mouseY))
        {
            start.onClick(mouseX,mouseY);
            return true;
        }

        return false;
    }

    public boolean hasAccount()
    {
        Minecraft mc=Minecraft.getInstance();
        User user =mc.getUser();
        if(!StorageAPI.loadNBTFromRoot(user.getName()+"/code").isEmpty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }



    @Override
    public boolean keyReleased(int keyCode, int scanCode, int modifiers) {

        if(isComfirmingQuit)
        {
            if(keyCode== InputConstants.KEY_ESCAPE)
            {
                quitComfirmCancel();
            }
        }

        if(keyCode== InputConstants.KEY_T)
        {
            this.test=true;
        }
        return super.keyReleased(keyCode,scanCode,modifiers);
    }
}
